import React, { useState, useEffect } from 'react'
import { useParams,useDispatch } from 'umi'
import { fetchItemDetail } from '@a'
import { Swiper, Button, Popup, Stepper  } from 'antd-mobile'
import Navbar from '@c/Navbar'
import './assets/style.scss'
export default function index() {
  const itemId = useParams().id;
  const [item, setItem] = useState({
    basicInfo: {},
    content: '',
    pics: []
  });
  // 点击商品图标 添加到购物车
  const dispatch = useDispatch();
  const addCartItem = (id: number) => {
    dispatch({
      type: 'cart/addItem',
      data: {
        goodsId: id,
        number: 1
      }
    })
  }
  
  const [sku, setSku] = useState({})
  // 请求商品详情
  const getItemDetail = () => {
    fetchItemDetail({ id: itemId }).then((res: { data: { code: number; data: { basicInfo: any; content: any; pics: any; }; }; }) => {
      if (res.data.code === 0) {
        setItem({
          basicInfo: res.data.data.basicInfo,
          content: res.data.data.content,
          pics: res.data.data.pics
        })
        setSku({
          ...res.data.data.basicInfo,
          number: 1
        })
      }
    })
  }
  // 控制 商品规格弹窗
  const [showSku, setShowSku] = useState(false);
  useEffect(() => {
    getItemDetail();
  }, [])
  return (
    <div className='detail'>
      <Navbar title={item.basicInfo.name||'详情页'} />
      <div className="container">
        <Swiper>
          {
            item.pics.map(pic => (
              <Swiper.Item key={pic.id}>
                <img src={pic.pic} alt="" />
              </Swiper.Item>
            ))
          }
        </Swiper>
        {item.basicInfo.name}
        <div dangerouslySetInnerHTML={{ __html: item.content }}></div>
      </div>
      {/* 商品行动栏 */}
      <div className="item-action">
        <Button size='large' color='danger' 
          clickCartIcon={ 
            (id: number) => {
              addCartItem(id)
            }
         }
        >加入购物车</Button>
        <Button size='large' color="primary">立即购买</Button>
      </div>
      {/* /商品行动栏 */}
      {/* 弹出商品规格 */}
      <Popup
        visible={showSku}
        showCloseButton
        onClose={() => {
          setShowSku(false)
        }}
        bodyStyle={{ padding: 15 }}
      >
        <div className="detail-item-pop">
          <img src={sku.pic} alt="" className="item-pic" />
          <div className="item-info">
            <h4>{sku.name}</h4>
            <div className="item-action">
              <p className="price">￥{sku.minPrice}</p>
              <Stepper
                defaultValue={sku.numer}
                onChange={value => {
                  setSku({
                    ...sku,
                    number: value
                  })
                }}
              />
            </div>
          </div>
        </div>
      </Popup>
      {/* 弹出商品规格 */}
    </div>
  )
}
